package com.chapter16.ThreadPoolExecutor;

import java.util.concurrent.*;

/**
 * @author 宋鑫宇
 * @version 1.0
 * 线程池的创建,并测试其特性
 */
public class ThreadPoolExecutor_ {
    public static void main(String[] args) {
        //创建 ThreadPoolExecutor 线程对象
        ExecutorService pool = new ThreadPoolExecutor(3, 5, 5,
                TimeUnit.SECONDS, new ArrayBlockingQueue<>(5),
                Executors.defaultThreadFactory(), new ThreadPoolExecutor.AbortPolicy());
        //2.给任务到线程池处理
        Runnable a = new A();
        //三个核心线程工作
        pool.execute(a);
        pool.execute(a);
        pool.execute(a);
        //更多线程进入线程队列
        pool.execute(a);
        pool.execute(a);
        pool.execute(a);
        pool.execute(a);
        pool.execute(a);
        //当线程队列满值时，新建临时线程
        pool.execute(a);
        pool.execute(a);
        //当临时线程和总线程数的和，达到设置的最大线程数时，再有新的线程会进行处理（新建线程时通过构造器设置的）
//        pool.execute(a);

        //关闭线程池（开发中一般不会使用）
//        pool.shutdownNow();//立即关闭线程池，会丢失任务
        pool.shutdown();//会等待全部任务执行完毕之后再关闭线程池
    }
}

class A implements Runnable {

    @Override
    public void run() {
        for (int i = 0; i < 5; i++) {
            System.out.println(Thread.currentThread().getName() + " " + i);
        }
        try {
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}